package com.cruise.game.common.api;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 全局异常处理器
 *
 * @author cruise
 * @date 2025-02-28
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(ApiException.class)
    public ApiResult<Object> handleApiException(ApiException e, HttpServletRequest request,
            HttpServletResponse response) {
        log.error("ApiException, URL:{}, message:{}", request.getRequestURI(), e.getMessage());

        // 根据错误码动态设置HTTP状态码
        int statusCode;
        switch (e.getCode()) {
            case ApiCode.UNAUTHORIZED:
                statusCode = HttpStatus.UNAUTHORIZED.value();
                break;
            case ApiCode.FORBIDDEN:
                statusCode = HttpStatus.FORBIDDEN.value();
                break;
            case ApiCode.PARAM_ERROR:
                statusCode = HttpStatus.BAD_REQUEST.value();
                break;
            case ApiCode.NOT_FOUND:
                statusCode = HttpStatus.NOT_FOUND.value();
                break;
            case ApiCode.METHOD_NOT_ALLOWED:
                statusCode = HttpStatus.METHOD_NOT_ALLOWED.value();
                break;
            case ApiCode.INTERNAL_SERVER_ERROR:
            case ApiCode.SYSTEM_ERROR:
                statusCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
                break;
            case ApiCode.SERVICE_UNAVAILABLE:
                statusCode = HttpStatus.SERVICE_UNAVAILABLE.value();
                break;
            case ApiCode.BUSINESS_ERROR:
            default:
                // 业务异常默认设置为400 Bad Request
                statusCode = HttpStatus.BAD_REQUEST.value();
        }

        response.setStatus(statusCode);
        return ApiResult.fail(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResult<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e,
            HttpServletRequest request) {
        log.error("MethodArgumentNotValidException, URL:{}, message:{}", request.getRequestURI(), e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        List<String> errors = new ArrayList<>();
        for (ObjectError error : bindingResult.getAllErrors()) {
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                errors.add(fieldError.getField() + ": " + fieldError.getDefaultMessage());
            } else {
                errors.add(error.getDefaultMessage());
            }
        }
        return ApiResult.paramError(String.join(", ", errors));
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResult<Object> handleConstraintViolationException(ConstraintViolationException e,
            HttpServletRequest request) {
        log.error("ConstraintViolationException, URL:{}, message:{}", request.getRequestURI(), e.getMessage());
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        List<String> errors = new ArrayList<>();
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            errors.add(constraintViolation.getMessage());
        }
        return ApiResult.paramError(String.join(", ", errors));
    }

    /**
     * 处理参数类型不匹配异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResult<Object> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e,
            HttpServletRequest request) {
        log.error("MethodArgumentTypeMismatchException, URL:{}, message:{}", request.getRequestURI(), e.getMessage());
        return ApiResult.paramError("参数类型不匹配, 参数" + e.getName() + "应为" + e.getRequiredType().getName() + "类型");
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResult<Object> handleException(Exception e, HttpServletRequest request) {
        log.error("Exception, URL:{}, message:{}", request.getRequestURI(), e.getMessage(), e);
        return ApiResult.systemError();
    }
}
